import { createSlice } from "@reduxjs/toolkit";
import { getToken, setToken, clearToken } from "@/utils/token";
import { login, logout } from "@/api/adminApi";

const loginSlice = createSlice({
  name: "login",
  initialState: {
    token: getToken() || "",
  },
  reducers: {
    setTokenValue: (state, tokenValue) => {
      state.token = tokenValue;
    },
  },
});

const { setTokenValue } = loginSlice.actions;

const Login = async (userInfo: any) => {
  const response = await login(userInfo);
  const { tokenValue } = response.data;
  await setToken(tokenValue);
  setTokenValue(tokenValue);
};

const Logout = async () => {
  const token = await getToken();
  await logout({ token });
  setTokenValue("");
  await clearToken();
};

export { Login, Logout };

export default loginSlice.reducer;
